package com.wyl.xyg.sample.service;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wyl.search.bean.SearchMessageBean;
import com.wyl.xyg.sample.model.Appointment;

/**
 * 这个是模板,开发参考用
 * @className: AppointmentServices
 * @date: 2016年5月11日 上午9:39:07
 * @author sunkxu
 * @version 0.1
 * @since JDK 1.8
 */
@Service
@Transactional(readOnly = true)
public class AppointmentServices {
	
	public static String sql = "select * from appointment a where a.name like '%$[_P_NAME]%' and a.telphone like '%$[_P_TELPHONE]%' and a.the_date between '$[START_DATE]' and '$[END_DATE]' and appid='$[APPID]'";
	public static String delSql = "delete from appointment where id in (XXX)";
			
	@PersistenceContext
	private EntityManager entityManager;
	
	@Transactional
	public void save(Appointment entity){
		entityManager.persist(entity);		
	}
	
	@Transactional
	public void update(Appointment entity){
		entityManager.merge(entity);		
	}
	
	public Appointment findById(long id){
		return entityManager.find(Appointment.class, id);	
	}
	
	@SuppressWarnings("unchecked")
	public List<Appointment> findAllAppointments(int page){
		return entityManager.createNativeQuery(Appointment.ALL, Appointment.class)
				.setFirstResult(page==1 ? 0 : (page-1) * SearchMessageBean.pageSize-1)
				.setMaxResults(SearchMessageBean.pageSize)
				.getResultList();	
	}
	
	@SuppressWarnings("unchecked")
	public List<Appointment> findAllAppointments(int page, String sql){
		return entityManager.createNativeQuery(sql , Appointment.class)
				.setFirstResult(page==1 ? 0 : (page-1) * SearchMessageBean.pageSize-1)
				.setMaxResults(SearchMessageBean.pageSize)
				.getResultList();	
	}
	
	@SuppressWarnings("unchecked")
	public List<Appointment> findAppointmentsByDatetime(int page, Date startDate, Date endDate){
		return entityManager.createNativeQuery(Appointment.BY_DATETIME, Appointment.class)
				.setParameter("startDatetime", startDate)
				.setParameter("endDatetime", endDate)
				.setFirstResult(0*page)
				.setMaxResults(SearchMessageBean.pageSize)
				.getResultList();	
	}
	
	@Transactional
	public int delAppointmentsById(String ...ids){
		StringBuffer buffer = new StringBuffer();
		for(String id : ids){
			buffer.append(id+",");
		}
		String temp = buffer.toString().substring(0,buffer.toString().length()-1);		
		return entityManager.createNativeQuery(delSql.replace("XXX", temp)).executeUpdate();	
	}
}
